package com.dtm.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ServerThread extends Thread implements SomethingHappenedInterface{
	private int clientID = 1000;
	private boolean stop;
	private ArrayList<ClientThread> clientsList = new ArrayList<ClientThread>();
	
	@Override
	public void run() {			
		try {
			ServerSocket serverSocket = new ServerSocket(2001);
			while(!stop) {
				Socket socket = serverSocket.accept();
				if (clientsList.size() < 5) {
					clientID++;
					ClientThread client = new ClientThread(socket, clientID, this);
					clientsList.add(client);
					client.start();
					new UpdateListServerSubThread(clientsList) {
					}.start();
				} else {
					new RefuseServerSubThread(socket){
					}.start();
				}
			}
		
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void clientDisconnect(int clientID) {
		for(int i = 0; i < clientsList.size(); i++) {
			if (clientsList.get(i).getClientID() == clientID) {
				clientsList.remove(i);
				i--;
			} else {
				clientsList.get(i).sendToRemoteDevice(""+ClientThread.CDC+clientID);
			}
		}
	}

	@Override
	public void clientChangeStatus(int clientID) {
		for(ClientThread participants : clientsList) {
			participants.sendToRemoteDevice(""+ClientThread.STC+clientID);
		}
	}
}